<?php

namespace App\Admin\Controllers;

use App\Models\ProfitSharingAccount as prAccount;
use App\Admin\Repositories\ProfitSharingAccount;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Log;
use App\Contracts\WxProfitSharing;
use Illuminate\Support\Facades\Artisan;

class ProfitSharingAccountController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ProfitSharingAccount(), function (Grid $grid) {
            $grid->id->sortable();
            $grid->name;
            $grid->sub_appid;
            $grid->sub_mchid;
            //$grid->pay_notify_url;
            $grid->created_at;
            $grid->updated_at->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('name');
                $filter->like('sub_appid');
                $filter->like('sub_mchid');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ProfitSharingAccount(), function (Show $show) {
            $show->id;
            $show->name;
            $show->sub_appid;
            $show->sub_mchid;
            //$show->pay_notify_url;
            $show->created_at;
            $show->updated_at;
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ProfitSharingAccount(['receivers']), function (Form $form) {
            $form->display('id');
            $form->text('name');
            $form->text('sub_appid');
            $form->text('sub_mchid');
            $form->text('app_certpem',__('cert证书路径'));
            $form->text('app_keypem',__('key证书路径'));
            $form->text('md5key',__('md5key密钥'));
            
            $form->switch('is_mch',__('是否是服务商'));
            //$form->text('pay_notify_url');

            $form->display('created_at');
            $form->display('updated_at');

            // 保存时触发的事件
            $form->saving(function (Form $form) {
                //return true;
                Log::info('后台管理分账saving');
                $receivers = $form->receivers;
                Log::info($form->receivers);
                
                
                if(!empty($receivers))
                {
                    // 分账接收方总金额百分比不能超过30%
                    $totalAmount = 0;
                    foreach ($receivers as $key => $receiver) {
                        if($receiver['_remove_'] == '1'){
                            continue;
                        }
                        $totalAmount += $receiver['amount'];
                    }
                    if($totalAmount>30){
                        return $form->error('分账接收方总金额百分比不能超过30%');
                    }
                    
                    $accountInfo = prAccount::where( 'sub_appid', $form->sub_appid )->where('sub_mchid', $form->sub_mchid)->first();
                    $app_certpem = $accountInfo['id'];
                  
                    // if( !file_exists($app_certpem.'/apiclient_cert.pem') ||!file_exists($app_certpem.'/apiclient_key.pem') ){
                    //     return $form->error("请上传证书，配置文件后再操作！");
                    // }
                    
                    $config = [
                        'appCertPem'=>$accountInfo->app_certpem,
                        'appKeyPem'=>$accountInfo->app_keypem,
                        'appId' => $accountInfo->sub_appid,
                        'mchId' => $accountInfo->sub_mchid,
                        'md5Key' => $accountInfo->md5key,
                        'is_mch' => $accountInfo->is_mch,
                    ];
                        
                    // 调用微信接口 添加or删除分账接收方
                    foreach ($receivers as $receiver) {
                        $postReceiver = [
                            'type'=>$receiver['type'],
                            'account'=>$receiver['account'],
                            'name'=>$receiver['name'],
                            'relation_type'=>$receiver['relation_type']
                        ];
	                    Artisan::call('config:clear');//清除缓存
                        
                        $wxProfitShare = new WxProfitSharing($config);
                        if($receiver['_remove_'] == '1'){
                            //删除
                            $res = $wxProfitShare->removeReceiver($form->sub_appid, $form->sub_mchid, $postReceiver);
                            Log::info($res);
                            if($res['return_code'] != 'SUCCESS' or $res['result_code'] != 'SUCCESS'){
                                return $form->error($res['err_code'].':'.$res['err_code_des']);
                            }
                        }else{
                            //添加
                            $res = $wxProfitShare->addReceiver($form->sub_appid, $form->sub_mchid, $postReceiver,$form->is_mch);
                            Log::info($res);
                            if($res['return_code'] != 'SUCCESS' or $res['result_code'] != 'SUCCESS'){
                                if(!empty($res['err_code'])){
                                    return $form->error($res['err_code'].':'.$res['err_code_des']);
                                }
                                return $form->error($res['return_code'].':'.$res['return_msg']);
                            }
                        }

                    }
                }

            });

            $form->deleting(function (Form $form){
                Log::info('deleting');
                $receivers = $form->receivers;
                Log::info($receivers);
            });

            $form->hasMany('receivers', '分帐接收方列表', function (Form\NestedForm $form) {
                $type = [
                    'MERCHANT_ID' => '商户ID',
                    'PERSONAL_OPENID' => '个人openid',
                    'PERSONAL_SUB_OPENID' => '个人sub_openid',
                ];

                $relation_type = [
                    'PARTNER' => '合作伙伴',
                    'DISTRIBUTOR' => '分销商',
                    'SUPPLIER' => '供应商',
                    'SERVICE_PROVIDER' => '服务商',
                    'STORE' => '门店',
                ];
                $form->select('type', '分账接收方类型')->options($type);
                $form->text('account', '分账接收方帐号');
                $form->text('name', '分账接收方全称');
                $form->select('relation_type', '与分账方的关系')->options($relation_type);
                $form->number('amount', '分账金额(%)');
                $form->text('desc', '收款方说明');
            });


        });
    }
}
